package com.xiaochuan.config;

import com.xiaochuan.mapper.UserMapper;
import com.xiaochuan.mapper.UserRoleMapper;
import com.xiaochuan.mapper.UserSysPrivilegeMapper;
import com.xiaochuan.pojo.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class UserRealm extends AuthorizingRealm {//自定义realm
    private static Logger log = LoggerFactory.getLogger(UserRealm.class);
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private UserSysPrivilegeMapper userSysPrivilegeMapper;

    @Override
    public String getName() {
        return "userRealm";
    }

    @Override//授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        log.info("--------------->授权");
        User user = (User)principals.iterator().next();
        Set<String> roleNames = userRoleMapper.selectUserRoleNames(user.getUserAccount());//角色名
        Set<String> sysPrivilege = userSysPrivilegeMapper.selectUserSysPrivilege(user.getUserAccount());//权限列表
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        info.setRoles(roleNames);//传入角色名
        info.setStringPermissions(sysPrivilege);//传入权限
        log.info("--------------->角色:"+user);
        return info;
    }

    @Override//认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        log.info("--------------->认证");
        UsernamePasswordToken usernamePasswordToken=(UsernamePasswordToken)token;
        String username = usernamePasswordToken.getUsername();

        User user=userMapper.selectUserAccount(username);
        log.info("--------------->认证参数："+user);
        if(user==null){
            return null;
        }

        return new SimpleAuthenticationInfo(user,user.getUserPassword(),getName());
    }
}
